package com.yango.teach.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yango.serviceutil.exception.YangoException;
import com.yango.teach.entity.Comment;
import com.yango.teach.entity.Course;
import com.yango.teach.entity.CourseDescription;
import com.yango.teach.entity.vo.course.*;
import com.yango.teach.mapper.CourseMapper;
import com.yango.teach.service.ChapterService;
import com.yango.teach.service.CourseDescriptionService;
import com.yango.teach.service.CourseService;
import com.yango.teach.service.VideoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author LiDingYin
 * @since 2021-07-24
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    //注入课程描述service
    @Autowired
    private CourseDescriptionService descriptionService;
    @Autowired
    private VideoService videoService;
    @Autowired
    private ChapterService chapterService;

    //保存课程基本信息-返回课程id
    @Override
    public String saveCourseInfo(CourseInfoForm courseInfoForm) {
        //判断课程对象是否为空
        if (StringUtils.isEmpty(courseInfoForm)) {
            throw new YangoException(20001, "课程信息不能为空!");
        }
        //添加课程基本信息
        Course course = new Course();//声明一个课程对象
        //将courseInfoForm的值复制到course中
        BeanUtils.copyProperties(courseInfoForm, course);
        //设置课程状态为未发布-Draft
        course.setStatus("Draft");
        //设置课程状态-0-未删除 1-已删除
        course.setIsDeleted(0);
        course.setCommentCount(0);
        //调用方法添加
        int insert = baseMapper.insert(course);
        if (insert < 1) {
            throw new YangoException(20001, "课程基本信息保存失败!");
        }
        //添加课程描述
        CourseDescription courseDescription = new CourseDescription();
        //设置课程id
        courseDescription.setId(course.getId());
        //设置课程简介
        courseDescription.setDescription(courseInfoForm.getDescription());
        //调用方法添加
        boolean save = descriptionService.save(courseDescription);
        if (!save) {
            throw new YangoException(20001, "课程详细信息保存失败!");
        }
        return course.getId();
    }

    //根据课程id获取课程基本信息
    @Override
    public CourseInfoForm getCourseInfoById(String courseId) {
        //查询课程基本信息
        Course course = this.getById(courseId);
        if (course == null) {
            throw new YangoException(20001, "没有查询到课程信息!");
        }
        //查询课程简介
        CourseDescription description = descriptionService.getById(courseId);
        CourseInfoForm courseInfoForm = new CourseInfoForm();
        //将courseInfo的信息复制到courseInfoForm中
        BeanUtils.copyProperties(course, courseInfoForm);
        if (course != null) {
            //向courseInfoForm中设置课程简介
            courseInfoForm.setDescription(description.getDescription());
        }

        //返回数据
        return courseInfoForm;
    }

    //更新课程基本信息
    @Override
    public boolean updateCourse(CourseInfoForm courseInfoForm) {
        //保存课程基本信息
        Course course = new Course();
        //course.setId(courseInfoForm.getId());//设置课程id
        //将courseInfoForm的值复制到course中
        BeanUtils.copyProperties(courseInfoForm, course);
        //调用方法修改
        boolean update = this.updateById(course);
        if (!update) {
            throw new YangoException(20001, "课程基本信息保存失败!");
        }

        //保存课程简介
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setDescription(courseInfoForm.getDescription());//设置课程简介
        courseDescription.setId(courseInfoForm.getId());//设置课程id
        //调用方法修改
        boolean flag = descriptionService.updateById(courseDescription);
        if (!flag) {
            throw new YangoException(20001, "课程描述信息保存失败!");
        }
        return true;
    }

    //课程确认信息
    @Override
    public CoursePublishVo getCoursePublish(String courseId) {
        return baseMapper.getCoursePublish(courseId);
    }

    //发布课程-修改课程状态为Normal
    @Override
    public boolean publishCourse(String courseId) {
        Course course = new Course();
        course.setId(courseId);//设置课程id
        course.setStatus("Normal");//设置课程状态
        Integer count = baseMapper.updateById(course);
        return count > 0 && count != null;
    }

    //课程列表-条件查询带分页
    @Override
    public void pageCourseList(Page<Course> pageParam, CourseQuery courseQuery) {
        //条件构造器
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");//根据创建时间降序排序
        //判断查询对象是否有值，没有-查询所有
        if (StringUtils.isEmpty(courseQuery)) {//为空
            //查询所有
            baseMapper.selectPage(pageParam, wrapper);
            return;
        }
        //构建条件
        if (!StringUtils.isEmpty(courseQuery.getTitle())) {//课程标题不为空
            //构建条件
            wrapper.like("title", courseQuery.getTitle());
        }
        if (!StringUtils.isEmpty(courseQuery.getTeacherId())) {//讲师id不为空
            //构建条件
            wrapper.eq("teacher_id", courseQuery.getTeacherId());
        }
        if (!StringUtils.isEmpty(courseQuery.getSubjectParentId())) {//一级分类id不为空
            //构建条件
            wrapper.eq("subject_parent_id", courseQuery.getSubjectParentId());
        }
        if (!StringUtils.isEmpty(courseQuery.getSubjectId())) {//二级分类id不为空
            //构建条件
            wrapper.eq("subject_id", courseQuery.getSubjectId());
        }
        //调用方法查询
        baseMapper.selectPage(pageParam, wrapper);
    }

    //删除课程
    @Override
    public boolean removeCourse(String courseId) {
        //根据课程id删除课时
        videoService.removeVideoByCourseId(courseId);

        //根据课程id删除章节
        chapterService.removeByCourseId(courseId);

        //根据课程id删除课程描述
        descriptionService.removeById(courseId);

        //删除课程封面    TODO

        //根据课程id删除课程
        Integer count = baseMapper.deleteById(courseId);
        return null != count && count > 0;
    }

    //根据讲师id查询讲师所讲课程
    @Override
    public List<Course> getByTeacherId(String teacherId) {
        QueryWrapper<Course> wrapper = new QueryWrapper<>();//条件构造器
        wrapper.eq("teacher_id", teacherId);//根据讲师id查询
        wrapper.orderByDesc("create_time");//根据创建时间查询
        return baseMapper.selectList(wrapper);//返回
    }

    //课程分类列表
    @Override
    public Map<String, Object> pageList(Page<Course> page, CourseFrontQuery courseFrontQuery) {
        //条件构造器
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        //判断课程标题是否为空
        if (!StringUtils.isEmpty(courseFrontQuery.getTitle())) {//不为空
            wrapper.like("title", courseFrontQuery.getTitle());//根据标题模糊查
        }
        //判断一级分类id是否为空
        if (!StringUtils.isEmpty(courseFrontQuery.getSubjectParentId())) {//不为空
            wrapper.eq("subject_parent_id", courseFrontQuery.getSubjectParentId());//根据一级分类id查询
        }
        //判断二级分类id是否为空
        if (!StringUtils.isEmpty(courseFrontQuery.getSubjectId())) {//不为空
            wrapper.eq("subject_id", courseFrontQuery.getSubjectId());//根据二级分类id查询
        }
        //判断讲师id是否为空
        if (!StringUtils.isEmpty(courseFrontQuery.getTeacherId())) {//不为空
            wrapper.eq("teacher_id", courseFrontQuery.getTeacherId());//根据讲师id查询
        }
        //判断销量是否为空
        if (!StringUtils.isEmpty(courseFrontQuery.getBuyCountSort())) {//不为空
            wrapper.orderByDesc("buy_count");//根据销量降序排序
        }
        //判断课程发布时间是否为空
        if (!StringUtils.isEmpty(courseFrontQuery.getCreateTimeSort())) {//不为空
            wrapper.orderByDesc("create_time");//根据发布时间降序排序
        }
        //判断价格是否为空
        if (!StringUtils.isEmpty(courseFrontQuery.getPrice())) {//不为空
            wrapper.orderByDesc("price");//根据价格降序排序
        }
        //调用方法查询课程信息
        baseMapper.selectPage(page, wrapper);
        //获取数据
        List<Course> records = page.getRecords();//记录集合
        long total = page.getTotal();//总记录数
        long current = page.getCurrent();//当前页
        long size = page.getSize();//当前页记录数
        long pages = page.getPages();//总页数
        boolean hasNext = page.hasNext();//是否有下一页
        boolean hasPrevious = page.hasPrevious();//是否有上一页
        //将数据封装进map集合
        Map<String, Object> map = new HashMap<>();
        map.put("items", records);
        map.put("total", total);
        map.put("current", current);
        map.put("size", size);
        map.put("pages", pages);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);
        //返回
        return map;
    }

    //根据课程id查询课程基本信息-用户界面
    @Override
    public CourseFrontVo getCourseById(String courseId) {
        this.updateViewCount(courseId);
        return baseMapper.getCourseById(courseId);
    }

    //更新课程浏览量
    @Override
    public void updateViewCount(String courseId) {
        //根据课程id查询课程信息
        Course course = baseMapper.selectById(courseId);
        //修改浏览量
        course.setViewCount(course.getViewCount() + 1);
        //修改
        baseMapper.updateById(course);
    }

    //统计每天新增课程数
    @Override
    public Integer getSaveCourseCount(String day) {
        return baseMapper.getSaveCourseCount(day);
    }


}
